<!DOCTYPE html>
[#escape x as (x)!?html]
<html lang="zh-CN">
  <head>
    <meta charset="utf-8" />
    <title>智能问答助手 - AI知识问答平台 - ${site.seoTitle} - Powered by JPROCMS</title>
    <meta name="keywords" content="${site.seoKey}" />
    <meta name="description" content="${site.seoDesc}" />
    [#include '../includes/common_res.html'/]
    <link rel="stylesheet" href="${resource}/static/css/robot.css">
  </head>
  <body>
    [#assign shadowNav=true/] [#include '../includes/header.html'/]
    <div class="container mt-1 main-body">
      <div class="row" >
        <!-- 主聊天区域 -->
        <div class="col-lg-8">
          <div class="chat-container">
            <div class="chat-header">
              <div class="d-flex align-items-center">
                <div class="avatar me-3">
                  <img src="${robotConfig.robotImg!}"/>
                </div>
                <div>
                  <h5 class="mb-0">${robotConfig.name!}</h5>
                  <small class="text-info">在线 - 随时为您解答问题</small>
                </div>
              </div>
            </div>

            <div class="chat-messages position-relative" id="chatMessages">
              <!-- 初始欢迎消息 -->
              <div class="message bot-message">
                <strong><i class="fas fa-robot me-2"></i>${robotConfig.name!}：</strong>
                ${robotConfig.welcomingWord!}
              </div>

              <div class="message bot-message">
                <strong><i class="fas fa-robot me-2"></i>大家都在问:</strong>
                [@ZRobotGuideTopList count='10';guides]
                <div class="py-2">
                  [#list guides  as guide]
                  <a href="#" onclick="guideClick('${guide.id}')"  class="btn btn-secondary btn-sm ml-2">${guide.title!}</a>
                  [/#list]
                </div>
                [/@ZRobotGuideTopList]
              </div>
              <!-- 滚动到底部按钮 -->
              <div class="scroll-down-btn" onclick="scrollToBottom()">
                <i class="fas fa-chevron-down"></i>
              </div>
            </div>
            <!-- 正在输入指示器 -->
            <div class="typing-indicator mt-2" id="aiRobotWorkingTip" style="display:none;">
              <span class="me-2">AI助手正在输入</span>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
            <div class="input-area">
              <div class="input-group">
                <input type="text" class="form-control chat-input" placeholder="输入您的问题..." id="userInput">
                <button class="btn send-btn" id="sendBtn">
                  <i class="fas fa-paper-plane"></i>
                </button>
              </div>
              <div class="mt-2 d-flex justify-content-between">
                <small class="text-muted">按Enter发送消息</small>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 - 常见问题 -->
        <div class="col-lg-4 sidebar">
          <div class="card faq-card mb-4">
            <div class="card-body">
              <div class="text-center mb-3">
                <h5 class="card-title">常见问题</h5>
              </div>
              <div class="list-group">
                [@ZRobotFaqList count='10' recommend='true';faqs]
                  [#list faqs as faq]
                    <a href="#" onclick="faqClick('${faq.id}')" class="list-group-item list-group-item-action d-flex align-items-center">
                      <div class="badge [#if faq_index==0]badge-danger[#elseif faq_index<=2]badge-warning text-white[#elseif faq_index<=4]badge-primary[#else]badge-secondary[/#if]"
                              style="width: 25px" >${faq_index+1}</div>
                      <div class="ml-2 text-truncate">${faq.title!}</div>
                    </a>
                  [/#list]
                [/@ZRobotFaqList]
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>

    [#include '../includes/footer.html'/] 
    [#include '../includes/inc_msg.html'/]
    <script>
      // 简单的聊天交互逻辑
      document.getElementById('sendBtn').addEventListener('click', sendMessage);
      document.getElementById('userInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          sendMessage();
        }
      });

      //文本输入框发送消息
      function sendMessage() {
        const userInput = document.getElementById('userInput');
        const message = userInput.value.trim();
        if (message) {
          // 添加用户消息
          addMessage(message, 'user');
          userInput.value = '';
          $("#aiRobotWorkingTip").show()
          let  conversation = Cms.getRobotAiConversation()
          //请求AI
          let queryUrl = "${api}/robot-faq/query?query="+message;
          if(conversation&&conversation!=0){
            queryUrl = queryUrl +"&conversationId="+conversation
          }
          axios.get(queryUrl,{
            timeout: 100000 // 设置超时时间为100秒
          })
          .then(function (response) {
            if (response.data.code === 0) {
              // AI回复
              const hitType = response.data.data.hitType
              const results = response.data.data.results
              addMultipleMessage(hitType,'bot',results)
              $("#aiRobotWorkingTip").hide()
            }
          });
        }
      }

      //聊天新增消息
      function addMessage(text, sender) {
        const chatMessages = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message');
        if (sender === 'user') {
          messageDiv.classList.add('user-message');
          messageDiv.innerHTML = '<strong><i class="fas fa-user me-2"></i>您：</strong>'+text;
        } else {
          messageDiv.classList.add('bot-message');
          messageDiv.innerHTML = '<strong><i class="fas fa-robot me-2"></i>AI助手：</strong>'+text;
        }
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
      }

      //引导词子层级消息添加
      function addGuideMessage(title,sender,childrens) {
        const chatMessages = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message');
        messageDiv.classList.add('bot-message');
        let robotReplyGideHtml  = '<strong><i class="fas fa-robot me-2"></i>您想了解关于“'+title+'”哪方面的内容？</strong>';
        robotReplyGideHtml = robotReplyGideHtml + '<div class="py-2">'
        for (let item of childrens) {
            robotReplyGideHtml = robotReplyGideHtml +'<a href="#" onclick="guideClick('+item.id+')"  class="btn btn-secondary btn-sm ml-2">'+item.title+'</a>'
        }
        robotReplyGideHtml = robotReplyGideHtml + '</div>'
        messageDiv.innerHTML = robotReplyGideHtml;
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
      }
      //添加多条搜索结果的消息
      //hitType 命中类型  1常见问题  2内容库 3AI
      function addMultipleMessage(hitType,sender,childrens) {
        const chatMessages = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message');
        messageDiv.classList.add('bot-message');
        let robotReplyHtml  = '';
        robotReplyHtml = robotReplyHtml + '<div class="py-2">'
        if(hitType==1){
          for (let item of childrens) {
            robotReplyHtml = robotReplyHtml +'<div><a href="#" onclick="faqClick('+item.id+')"  class="btn  btn-sm ml-2">'+item.title+'</a></div>'
          }
        }else if(hitType==2){
          for (let item of childrens) {
            let title = item.title
            if(title.length>30){
              title = title.substring(0,30)+"..."
            }
            robotReplyHtml = robotReplyHtml +'<div><a href="'+item.linkUrl+'"  target="_blank" class="btn  btn-sm ml-2">'+title+'</a></div>'
          }
        }else {
          robotReplyHtml = robotReplyHtml +'<strong><i class="fas fa-robot me-2"></i>AI助手：</strong>'+childrens[0].replyText;
        }
        robotReplyHtml = robotReplyHtml + '</div>'
        messageDiv.innerHTML = robotReplyHtml;
        chatMessages.appendChild(messageDiv);
        scrollToBottom();
      }

      function scrollToBottom() {
        const chatMessages = document.getElementById('chatMessages');
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }
      //常见问题点击
      function faqClick(id) {
        axios.get("${api}/robot-faq/getFaq/"+id)
        .then(function (response) {
          if (response.data.code === 0) {
            // AI回复
            if(response.data.data.toLink){
                window.open(response.data.data.linkUrl)
            }else{
               // 添加用户消息
              addMessage(response.data.data.title, 'user')
              addMessage(response.data.data.replyText, 'bot');
            }
          }
        });
      }
      //引导词点击
      function guideClick(id) {
        axios.get("${api}/robot-faq/getGuide/"+id)
        .then(function (response) {
          if (response.data.code === 0) {
            // 添加用户消息
            addMessage(response.data.data.title, 'user')
            //如果有引导词则返回子引导词
            if(response.data.data.children){
                // AI回复
                setTimeout(() => {
                  addGuideMessage(response.data.data.title, 'bot',response.data.data.children);
                }, 100);
            }else{
             //没有子引导词在返回自身
                // AI回复
                setTimeout(() => {
                  addMessage(response.data.data.guide.replyText, 'bot');
                }, 100);
            }
          }
        });
      }
      function initConversation() {
        let  conversation = Cms.getRobotAiConversation()
        console.log(conversation)
        if(!conversation){
          axios.post("${api}/robot-faq/ai/chat/createConversation",{"visitor":Cms.getUniqueVisitor()})
          .then(function (response) {
            if (response.data.code === 0) {
              conversation = response.data.data
              Cms.setRobotAiConversation(conversation)
            }
          });
        }
      }
      // 初始滚动到底部
      window.onload = scrollToBottom;
      $(function () {
        initConversation()
      });
    </script>
  </body>
</html>
[/#escape]
